package com.spring_mysql_redis.service.impl;


import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spring_mysql_redis.entity.Users;
import com.spring_mysql_redis.mapper.UsersMapper;
import com.spring_mysql_redis.model.ResultFormat;
import com.spring_mysql_redis.service.UsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spring_mysql_redis.utils.RedisUtil;
import com.spring_mysql_redis.utils.ResultUtil;

import com.spring_mysql_redis.utils.TokenUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 */
@Service
@Transactional
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    private Logger logger = LoggerFactory.getLogger(UsersService.class);

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private TokenUtil tokenUtil;


    /**
     * 分页查询用户信息
     *
     * @param users
     * @param page
     * @param limit
     * @return
     */
    @Override
    public IPage<Users> selectUsersList(Users users, Integer page, Integer limit) {
        AbstractWrapper wrapper = new QueryWrapper<Users>();
        if (users != null) {
            if (!StringUtils.isEmpty(users.getUserName())) {
                wrapper.like("user_name", users.getUserName());
            }

        }
        //查询状态为0 的数据
        /*wrapper.eq("state", 0);*/
        /**
         * 对查询数据进行排序(根据注册时间进行排序)
         * orderByAsc:升序
         * orderByDesc:降序
         */
        wrapper.orderByAsc("create_time");
        Page<Users> iPage = new Page<Users>(page, limit);
        Page<Users> pgLinksPage = usersMapper.selectPage(iPage, wrapper);
        return pgLinksPage;
    }

    /**
     * 分页模糊查询用户信息
     *
     * @param users
     * @param page
     * @param limit
     * @return
     */
    @Override
    public IPage<Users> selectUsers(Users users, Integer page, Integer limit) {
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        if (users != null) {
            if (!StringUtils.isEmpty(users.getNickname()) || !StringUtils.isEmpty(users.getUuId())) {
                wrapper.like("nickname", users.getNickname()).or().like("uu_id", users.getUuId());
            }

        }
        //查询状态为0 的数据
        /*wrapper.eq("state", 0);*/
        /**
         * 对查询数据进行排序(根据注册时间进行排序)
         * orderByAsc:升序
         * orderByDesc:降序
         */
        wrapper.orderByAsc("create_time");
        Page<Users> iPage = new Page<Users>(page, limit);
        Page<Users> pgLinksPage = usersMapper.selectPage(iPage, wrapper.select(Users.class, f ->
                ! f.getColumn().equals("password") && ! f.getColumn().equals("email") && ! f.getColumn().equals("telephone_number") && ! f.getColumn().equals("state")
        ));
        return pgLinksPage;
    }


    /**
     * 添加
     *
     * @param users
     * @return
     */
    @Override
    public ResultFormat saveUsers(Users users) {
        logger.info("-----------------进入service实现层 添加用户信息-----------------");

        /**
         * 查询用户名称是否存在
         * 如果存在那就返回提示已经存在
         * 如果不存在就执行添加
         */
        AbstractWrapper abstractWrapper = new QueryWrapper<Users>();
        abstractWrapper.eq("user_name", users.getUserName());
        Users UsersWrapperGet = usersMapper.selectOne(abstractWrapper);
        logger.info("pgLabelsWrapperGet={}", UsersWrapperGet);

        if (UsersWrapperGet != null) {
            return ResultUtil.error(101, "用户名称已存在");
        }
        users.setPassword(DigestUtils.md5Hex(users.getPassword()));
        users.setState(0);

        Integer insert = usersMapper.insert(users);

        if (insert > 0) {
            redisUtil.lSet("userId", users.getId());
            redisUtil.set("users:" + users.getId(), users);
        }
        return ResultUtil.success();
    }

    /**
     * 修改
     *
     * @param users
     * @return
     */
    @Override
    public Integer updateUsers(Users users) {
        logger.info("-----------------进入service实现层 修改用户信息-----------------");
        /**
         * 查询标签名称是否存在
         * 如果存在那就返回提示已经存在
         * 如果不存在那就修改
         */
        if (users != null) {
            users.setPassword(DigestUtils.md5Hex(users.getPassword()));
            if (users.getId() != null && !users.getUserName().isEmpty()) {
                Users pgLabelsByIdInfo = usersMapper.selectById(users.getId());
                AbstractWrapper wrapper = new QueryWrapper();
                wrapper.eq("user_name", users.getUserName());
                Users pgLabelsByNameInfo = usersMapper.selectOne(wrapper);
                /**
                 * 如果通过id查询的用户信息与前台传过来的名称一致
                 * 可修改其它数据
                 */
                if (pgLabelsByIdInfo != null) {
                    logger.info("pgLabelsByIdInfo={}", pgLabelsByIdInfo);
                    if (pgLabelsByIdInfo.getUserName().equals(users.getUserName())) {
                        Integer updateById = usersMapper.updateById(users);
                        if (updateById > 0) {
                            redisUtil.set("users:" + users.getId(), users);
                            return 200;
                        }
                    }
                }

                /**
                 * 从前台传过来的用户名称与id查询的名称不一致
                 * 再通过名称查询的数据为空就可以修改
                 */
                if (pgLabelsByNameInfo != null) {
                    logger.info("pgLabelsByNameInfo={}", pgLabelsByNameInfo);
                    if (!pgLabelsByNameInfo.getUserName().equals(pgLabelsByIdInfo.getUserName())) {
                        return 101;
                    }
                }

            }
        }

        /**
         * 如果用户名名称不一致就修改成 不存在的用户名称
         */
        Integer updateById = usersMapper.updateById(users);
        if (updateById > 0) {
            redisUtil.set("label:" + users.getUserName(), users);

        }

        return 100;
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public Integer deleteUsersId(Integer id) {
        logger.info("-----------------进入service实现层 删除用户信息-----------------");
        Integer deleteById = usersMapper.deleteById(id);
        if (deleteById > 0) {
            Long delete = redisUtil.delete("users:" + String.valueOf(id));
            return 200;
        }
        return deleteById;
    }

    @Override
    public ResultFormat selectLogin(String userName, String password) {
        logger.info("-----------------进入service实现层 登录用户信息-----------------");
        if (userName != null && password != null){
            AbstractWrapper wrapper = new QueryWrapper();
            wrapper.eq("user_name", userName);
            Users user = usersMapper.selectOne(wrapper);
            if (user != null){
                if(user.getPassword().equals(DigestUtils.md5Hex(password))){
                    String token=tokenUtil.getToken(user);
                    redisUtil.set(token, user.getId(), 3600);//一小时
                    Map<String,String> data=new HashMap<>();
                    data.put("token",token);
                    data.put("userId",user.getId()+"");
                    data.put("uuId",user.getUuId());
                    data.put("nickname",user.getNickname());
                    data.put("icon",user.getIcon());
                    return ResultUtil.success(data);
                }
            }
        }
        return ResultUtil.error(100, "登录失败");
    }

    @Override
    public Integer upUsers(Users user) {
        if (user != null) {
            if (user.getId() != null && !user.getUserName().isEmpty()) {
                Integer updateById = usersMapper.updateById(user);
                if (updateById > 0) {
                    redisUtil.set("users:" + user.getId(), user);
                    return 200;
                }
            }
        }
        return 100;
    }

}
